import React, { useState, useEffect } from "react";
import {
  Card,
  Input,
  Row,
  Col,
  Button,
  Table,
  Pagination,
  Modal,
  Form,
  Checkbox,
  Divider,
} from "antd";
import {
  SearchOutlined,
  UserOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
import type { ColumnsType } from "antd/es/table";

import {
  reqUserList,
  reqAddOrUpdateUser,
  reqDeleteUser,
  reqAssignData,
  reqAddAssign,
} from "@api/acl/user"; // 请求函数

const CheckboxGroup = Checkbox.Group;

interface IUserList {
  deleted: boolean;
  gmtCreate: string;
  gmtModified: string;
  id: string;
  nickName: string;
  password: string;
  roleName: string;
  salt: null;
  token: null;
  username: string;
}

export default function User() {
  const [currentPage, setCurrentPage] = useState<number>(1); // 当前页码
  const [pageSize, setPageSize] = useState<number>(5); // 每页条数
  const [username, setUsername] = useState<string>(""); // 搜索关键字
  const [userList, setUserList] = useState<any>([]); // 用户列表数据
  const [total, setTotal] = useState<number>(0); // 用户数据总数
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false); // dialog对话框的状态 -> 添加或修改用户数据
  const [isModalAssign, setIsModalAssign] = useState<boolean>(false); // dialog对话框的状态 -> 角色分配
  const [selected, setSelected] = useState<any>([]); // 批量删除 -> 被选中的用户
  const [allRolesList, setAllRolesList] = useState<any>([]); // 角色数据
  const [assignRoles, setAssignRoles] = useState<any>([]); // 已选角色数据name
  const [allRolesListName, setAllRolesListName] = useState<any>([]); // 角色数据name
  const [indeterminate, setIndeterminate] = useState(true); // 全选框半选状态
  const [checkAll, setCheckAll] = useState(false); // 全选框全选状态
  const [userParams, setUserParams] = useState<any>({
    id: "",
    username: "",
    nickName: "",
    password: "",
  }); // 添加或修改用户数据的参数

  useEffect(() => {
    getUserList(currentPage, pageSize); // 获取用户列表
  }, []);

  // 获取用户列表
  const getUserList = async (
    page: number,
    limit: number,
    username = "",
    nickName = ""
  ) => {
    const result = await reqUserList({
      page,
      limit,
      username,
      nickName,
    });
    setUserList(result.items);
    setTotal(result.total);
  };

  // 获取搜索关键字，查找数据
  const getUsername = (event: any) => {
    setUsername(event.target.value);
  };

  // 搜索按钮的回调 -> 按照关键字查找用户
  const searchBtn = () => {
    getUserList(1, pageSize, username);
    setCurrentPage(1);
    setUsername("");
  };

  // 清空搜索框
  const clearInput = () => {
    setUsername("");
  };

  // 添加按钮的回调
  const addUser = () => {
    setIsModalOpen(true);
    setUserParams({
      id: "",
      username: "",
      nickName: "",
      password: "",
    });
  };

  // 确定添加或修改的回调
  const handleOk = async () => {
    await reqAddOrUpdateUser(userParams);
    getUserList(userParams.id ? currentPage : 1, pageSize);
    !userParams.id && setCurrentPage(1);
    setIsModalOpen(false);
  };

  // 取消添加或修改的回调
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 获取用户名关键字
  const changeUsername = (event: any) => {
    userParams.username = event.target.value;
    setUserParams({ ...userParams });
  };

  // 获取用户昵称关键字
  const changeNickName = (event: any) => {
    userParams.nickName = event.target.value;
    setUserParams({ ...userParams });
  };

  // 获取用户密码关键字
  const changePassword = (event: any) => {
    userParams.password = event.target.value;
    setUserParams({ ...userParams });
  };

  // 修改用户按钮的回调
  const updateUser = (user: any) => {
    return () => {
      setUserParams(user);
      setIsModalOpen(true);
    };
  };

  // 批量删除用户
  const deleteUser = async () => {
    const list: any = [];
    selected.forEach((item: any) => {
      const resultPro = reqDeleteUser(item.id);
      list.push(resultPro);
    });

    try {
      await Promise.all(list);
      getUserList(1, pageSize);
      setCurrentPage(1);
    } catch (error: any) {
      alert(error.message);
    }
  };

  // 删除某个用户
  const deleteOneUser = (record: any) => {
    return async () => {
      await reqDeleteUser(record.id);
      getUserList(
        userList.length > 1 ? currentPage : currentPage - 1,
        pageSize
      );
      userList.length <= 1 && setCurrentPage(currentPage - 1);
    };
  };

  // 确定分配角色按钮的回调
  const assignHandleOk = async () => {
    const roleId = allRolesList
      .filter((role: any) => {
        return assignRoles.some((item: any) => {
          return role.roleName === item;
        });
      })
      .map((newRole: any) => newRole.id)
      .join();
    await reqAddAssign(userParams.id, roleId);
    getUserList(currentPage, pageSize);
    setIsModalAssign(false);
  };

  // 取消分配角色按钮的回调
  const assignHandleCancel = () => {
    setIsModalAssign(false);
  };

  // 分配角色按钮的回调 -> 获取角色数据及用户已有角色的数据
  const assignAddHandler = (record: any) => {
    return async () => {
      const result = await reqAssignData(record.id);
      setAllRolesList(result.allRolesList);
      setAllRolesListName(
        result.allRolesList.map((item: any) => item.roleName)
      );
      setAssignRoles(result.assignRoles.map((item: any) => item.roleName));
      setCheckAll(result.allRolesList.length === result.assignRoles.length);
      setIndeterminate(
        result.assignRoles.length > 0 &&
          result.assignRoles.length < result.allRolesList.length
      );
      setUserParams(record);
      setIsModalAssign(true);
    };
  };

  //   分配角色 -> 点击全选的回调
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setAssignRoles(e.target.checked ? allRolesListName : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  // 选中某一个角色是的回调
  const onChange = (list: CheckboxValueType[]) => {
    setAssignRoles(list);
    setIndeterminate(!!list.length && list.length < allRolesListName.length);
    setCheckAll(list.length === allRolesListName.length);
  };

  const columns: ColumnsType<IUserList> = [
    {
      title: "序号",
      render: (text: any, record: any, index: any) => {
        return index + 1;
      },
      align: "center",
    },
    {
      title: "用户名",
      dataIndex: "username",
    },
    {
      title: "用户昵称",
      dataIndex: "nickName",
    },
    {
      title: "角色列表",
      dataIndex: "roleName",
    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
    },
    {
      title: "更新时间",
      dataIndex: "gmtModified",
    },
    {
      title: "操作",
      align: "center",
      render: (text: any, record: any, index: any) => (
        <>
          <Button
            danger
            type="primary"
            icon={<UserOutlined />}
            onClick={assignAddHandler(record)}
          />
          <Button
            type="primary"
            style={{ margin: "0 10px" }}
            icon={<FormOutlined />}
            onClick={updateUser(record)}
          />
          <Button
            danger
            type="primary"
            icon={<DeleteOutlined />}
            onClick={deleteOneUser(record)}
          />
        </>
      ),
    },
  ];

  return (
    <Card>
      {/* 搜索框 - 搜索按钮 - 清空按钮 */}
      <Row gutter={16} style={{ marginBottom: "30px" }}>
        <Col className="gutter-row" span={3}>
          <Input value={username} onChange={getUsername} placeholder="用户名" />
        </Col>
        <Col className="gutter-row" span={21}>
          <Button type="primary" icon={<SearchOutlined />} onClick={searchBtn}>
            搜索
          </Button>
          <Button style={{ marginLeft: "20px" }} onClick={clearInput}>
            清空
          </Button>
        </Col>
      </Row>
      {/* 添加按钮 */}
      <Button type="primary" onClick={addUser}>
        添加
      </Button>
      {/* 批量删除按钮 */}
      <Button
        type="primary"
        style={{ marginLeft: "20px" }}
        danger
        onClick={deleteUser}
      >
        批量删除
      </Button>
      {/* 用户列表 */}
      <Table
        style={{ margin: "20px 0" }}
        bordered
        columns={columns}
        dataSource={userList}
        pagination={false}
        rowKey="id"
        rowSelection={{
          onSelectAll: (selected, selectedRows, changeRows) => {
            setSelected(changeRows);
          },
          onSelect: (record, selected, selectedRows) => {
            setSelected(selectedRows);
          },
        }}
      />
      {/* 分页器 */}
      <Pagination
        total={total}
        current={currentPage}
        pageSize={pageSize}
        showSizeChanger
        showQuickJumper
        pageSizeOptions={[5, 10, 15, 20]}
        showTotal={(total) => `共 ${total} 条`}
        onChange={(page, limit) => {
          setCurrentPage(page);
          setPageSize(limit);
          getUserList(page, limit);
        }}
      />
      {/* dialog对话框框 -> 添加用户或管理用户 */}
      <Modal
        title={userParams.id ? "修改用户" : "添加用户"}
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input value={userParams.username} onChange={changeUsername} />
          </Form.Item>
          <Form.Item
            label="用户昵称"
            rules={[{ required: true, message: "请输入用户昵称" }]}
          >
            <Input value={userParams.nickName} onChange={changeNickName} />
          </Form.Item>
          {!userParams.id && (
            <Form.Item
              label="用户密码"
              rules={[{ required: true, message: "请输入用户密码" }]}
            >
              <Input value={userParams.password} onChange={changePassword} />
            </Form.Item>
          )}
        </Form>
      </Modal>
      {/* dialog对话框框 -> 用户角色分配 */}
      <Modal
        title="角色分配"
        visible={isModalAssign}
        onOk={assignHandleOk}
        onCancel={assignHandleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input
              value={userParams.username}
              disabled
              onChange={changeUsername}
            />
          </Form.Item>
          <Form.Item label="角色列表">
            <Checkbox
              indeterminate={indeterminate}
              onChange={onCheckAllChange}
              checked={checkAll}
            >
              全选
            </Checkbox>
            <Divider />
            <CheckboxGroup
              options={allRolesListName}
              value={assignRoles}
              onChange={onChange}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
